package cn.lcc.utils.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.HexUtil;
import hy.iot.core.support.IotFieldTranseSupport;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * @author 21341
 */
@Slf4j
public class WatchSessionHandler extends SimpleChannelInboundHandler<byte[]> {

    private IotFieldTranseSupport support;

    public WatchSessionHandler(IotFieldTranseSupport sp) {
        this.support = sp;
    }

    // 关闭链接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handler removed {}", ctx.name());
//        watchSessionManagement.removed(ctx);
        ctx.close();
    }

    //链接异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("session exception with {} exception: {}", ctx.name(), ExceptionUtil.stacktraceToString(cause,Integer.MAX_VALUE));
        ctx.close();
    }

    /**
     * 注册 第一
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info(" 通道注册 {} _ {}", ctx.name(), ctx.channel().id().toString());
        ctx.fireChannelRegistered();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.error("channel 移除 {} _ {}", ctx.name(), ctx.channel().id().toString());
//        watchSessionManagement.removed(ctx);
        ctx.close();
    }

    // 接收处理消息
    @Override
    public void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
//        log.info("msg: {}", HexUtil.encodeHexStr(msg));
        support.mergeFrom(HexUtil.encodeHexStr(msg),ctx);
//        support.mergeFrom(new String(msg),ctx);
    }


    /**
     * 用户事件触发
     * 心跳检测状态去关闭连接的就写在这里！
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                //读空闲事件触发
//                String removed = watchSessionManagement.removed(ctx);
//                log.error("{} 读空闲事件触发", removed);
                ctx.channel().close();
            }
        }
    }


}
